package com.taptech.doufu.util;

import android.content.Intent;
import android.graphics.Color;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;

import com.taptech.doufu.ui.activity.NewOthersPersonalActivity;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.ui.view.DiaobaoTextView;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by longsiyang on 15/11/16.
 */
public class TextAtClickHelper {



    static public CharSequence getSpanString(DiaobaoTextView textView, CharSequence content) {
        if (textView != null && !TextUtil.isEmpty(textView.getText().toString())) {
            textView.setMovementMethod(LinkMovementMethod.getInstance());
            SpannableString spannableString = getClickString(content);
            return spannableString;
        }
        return null;
    }


    static private SpannableString getClickString(CharSequence content) {
        SpannableString spannableString = new SpannableString(content);
        Pattern p = Pattern.compile("(@[^@\\s#]{2,})");
        Matcher m = p.matcher(content);
        while (m.find()) {
            int start = m.start();
            int end = m.end();
            CharSequence tempString = content.subSequence(start + 1, end);
            spannableString.setSpan(new Clickable(tempString), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannableString;
    }


    static private class Clickable extends ClickableSpan implements View.OnClickListener {

        CharSequence atClickContent;

        public Clickable(CharSequence content) {
            atClickContent = content;
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(Color.parseColor("#ff6e70"));
            // 去掉下划线
            ds.setUnderlineText(false);
        }

        @Override
        public void onClick(View view) {
            Intent intent = new Intent(view.getContext(), NewOthersPersonalActivity.class);
            intent.putExtra(Constant.USERNICKNAME, atClickContent.toString());
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            view.getContext().startActivity(intent);
        }
    }


}
